All files / koajs-toolkit - Copie/lib loggerLib.js

92.62% Statements 113/122
91% Branches 91/100
100% Functions 18/18
92.62% Lines 113/122

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261    2x   2x   2x 1x 1x     2x   9x 9x   9x 9x 9x   9x 601x 174x   427x         9x                           9x                 9x 1x     9x 5x   5x   5x               5x   9x 3x     9x                     9x 9x 9x 9x   9x 9x     9x 103x 24x 24x     103x 103x 103x   103x 12x 91x 16x 75x 12x 63x 60x 20x   40x     3x       9x 46x 6x   40x       9x 39x 3x   36x       9x 36x 36x 12x   24x   36x                 2x   1x 1x 1x   1x 33x 8x   25x     1x 9x 1x 1x 8x 4x   4x     1x 8x 4x   4x     1x 8x 4x   4x     1x 8x 4x   4x     1x 8x 4x   4x     1x 9x 1x 1x 8x 4x   4x     1x 8x 4x   4x     1x 8x 4x   4x           2x   1x                                                    
'use strict';
 
const debug=require('debug')('koajs-toolkit:loggerLib');
 
let allLoggers={};
 
exports.getLogger = function getLogger(name){
    name = name || 'default';
    return allLoggers[name];
};
 
exports.Logger = class Logger {
    constructor(conf,name) {
        name = name || 'default';
        conf=conf || {};
 
        debug('%s', 'try to import winston');
        const winston = require('winston');
        debug('%s', 'import winston sucessful');
 
        const myFormat = winston.format.printf(({ level, message, timestamp }) => { //label,
            if (typeof message === 'object'){
                return `${timestamp} ${level}: ${JSON.stringify(message)}`;//[${label}]
            }else{
                return `${timestamp} ${level}: ${message}`;//[${label}]
            }
        });
 
        let loggerW;
        Iif(conf && conf.gg_stackdriver && conf.gg_stackdriver.toString()==='true'){
            // Imports the Google Cloud client library for Winston
            const {LoggingWinston} = require('@google-cloud/logging-winston');
            const loggingWinston = new LoggingWinston();
            loggerW=winston.createLogger({
                level: conf.level || undefined,
                transports: [
                    new winston.transports.Console(),
                    // Add Stackdriver Logging
                    loggingWinston,
                ],
            });
        }else{
 
            loggerW=winston.createLogger({
                level: conf.level || undefined,
                format: winston.format.combine(
                    winston.format.timestamp(),
                    // w(inston.format.label({ label: 'right meow!' }),
                    myFormat
                )
            });
 
            if(conf && conf.file && conf.file.maxsize){
                conf.file.maxsize=conf.file.maxsize * 1024 * 1024;
            }
 
            if(conf && conf.console){
                loggerW.remove(winston.transports.Console);
 
                Eif(conf.console.colorize){
 
                    conf.console.format= winston.format.combine(
                        winston.format.colorize(),
                        winston.format.timestamp(),
                        // winston.format.label({ label: 'right meow!' }),
                        myFormat
                    );
                }
 
                loggerW.add(new winston.transports.Console(conf.console));
            }
            if(conf && conf.file){
                loggerW.add(new winston.transports.File(conf.file));
            }
 
            Iif(conf && conf.replaceNodeJsConsole){
                console.log=this.verbose;
                console.error=this.error;
                console.warn=this.warn;
                console.info=this.info;
                console.debug=this.debug;
                console.trace=this.silly;
            }
        }
 
        // Object.setPrototypeOf(myLogger.prototype, myLogger);
        this.__proto__=loggerW;
        this.name=name;
        this.genuine_log=this.log;
        this.log=this.#log_with_compatibility;
 
        allLoggers[name]=this;
        return this;
    }
    
    #log_with_compatibility=function(a,b,...c){
        if(a && a.level && a.message){
            b=a.message;
            a=a.level;
        }
        
        a=a || null;
        b=b|| null;
        c=c || [];
 
        if(a==='debug'){
            this.debug(b,...c);
        }else if(a==='error'){
            this.error(b,...c);
        }else if(a==='hack'){
            this.hack(b,...c);
        }else if(a==='silly' || a==='verbose' || a==='http' || a==='info' || a==='warn'){
            if (typeof b === 'object'){
                this.genuine_log(a,  { message: b },...c);
            }else{
                this.genuine_log(a,b,...c);
            }
        } else{
            this.error(a,b,...c);
        }
    };
    
    error=function(a,...b){
        if(a && a.message){
            this.genuine_log('error',a.message,...b);
        }else{
            this.genuine_log('error',{ message: a },...b);
        }
    };
    
    debug=function(a,...b){
        if(a && a.stack){
            this.genuine_log('debug',a.stack,...b);
        }else{
            this.genuine_log('debug',{ message: a },...b);
        }
    };
 
    hack=function(m){
        let message ='';
        if (typeof m === 'object'){
            message= JSON.stringify(m);
        }else{
            message=m;
        }
        this.warn([
            '\x1b[47m', // background white
            '\x1b[31;1m' +'HACK WARNING:' , // bold red
            '\x1b[30;1m'+ message , // bold black
            '\x1b[0m' // reset
        ].join(' '));
    };
};
 
exports.LoggerForContext = class LoggerForContext {
    constructor(logger,uuid) {
        let prefix='';
        Eif(typeof uuid ==='string'){
            prefix=uuid+' - ';
        }
        this.log=function(a,b,...c){
            if (typeof b === 'object'){
                logger.log(a, prefix + JSON.stringify(b),...c);
            }else{
                logger.log(a, prefix + b);
            }
        };
        this.error=function(a){
            if (typeof a === 'object' && a instanceof Error){
                a.message=prefix + a.message;
                logger.error(a);
            }else if (typeof a === 'object'){
                logger.error(prefix + JSON.stringify(a));
            }else{
                logger.error(prefix + a);
            }
        };
        this.warn=function(a){
            if (typeof a === 'object'){
                logger.warn(prefix + JSON.stringify(a));
            }else{
                logger.warn(prefix + a);
            }
        };
        this.info=function(a){
            if (typeof a === 'object'){
                logger.info(prefix + JSON.stringify(a));
            }else{
                logger.info(prefix + a);
            }
        };
        this.http=function(a){
            if (typeof a === 'object'){
                logger.http(prefix + JSON.stringify(a));
            }else{
                logger.http(prefix + a);
            }
        };
        this.verbose=function(a){
            if (typeof a === 'object'){
                logger.verbose(prefix + JSON.stringify(a));
            }else{
                logger.verbose(prefix + a);
            }
        };
        this.debug=function(a){
            if (typeof a === 'object' && a instanceof Error){
                a.message=prefix + a.message;
                logger.debug(a);
            }else if (typeof a === 'object'){
                logger.debug(prefix + JSON.stringify(a));
            }else{
                logger.debug(prefix + a);
            }
        };
        this.silly=function(a){
            if (typeof a === 'object'){
                logger.silly(prefix + JSON.stringify(a));
            }else{
                logger.silly(prefix + a);
            }
        };
        this.hack=function(a){
            if (typeof a === 'object'){
                logger.hack(prefix + JSON.stringify(a));
            }else{
                logger.hack(prefix + a);
            }
        };
    }
};
 
exports.LoggerAsync = async function LoggerAsync (conf,name) {
 
    return await new exports.Logger (conf,name);
    // eslint-disable-next-line no-async-promise-executor
    // return new Promise(async (resolve, reject) => { 
    //     try{
    //         const l = await new exports.Logger (conf,name);
    //         resolve (l);
    //     }catch(e){
    //         reject(e);
    //     }
    // });
};
 
// exports.asyncClass = class AsyncClass {
//     constructor(logger,uuid) {
//         debug('%s', 'construct');
//         return new Promise (resolve=>{
//             debug('%s', 'before resolve');
//             setTimeout(()=>{
//                 debug('%s', 'before setTimeout resolve');
//                 resolve(this);
//                 debug('%s', 'after setTimeout resolve');
 
//             },2000)
//         })
//     }
//     a="oui";
// }